#include "main.h"

void walk_bookmark_array(json_t *root, json_t *bookmark_array, ptr_cfglst config)
{
    json_t *item;
    const char *type, *name;
    size_t array_size = json_array_size(bookmark_array);

    for (size_t i = 0; i < array_size; i++) {
        item = json_array_get(bookmark_array, i);
        type = json_string_value(json_object_get(item, "type"));
        name = json_string_value(json_object_get(item, "name"));

        if (strcmp(type, "url") == 0) {
            ptr_cfglst rule = get_matched_rule(config, name);
            if (!rule) {
#ifdef DEBUG
                printf("No any rule matched %s\n", name);
#endif
                continue;
            }
            json_t *folder = get_folder(root, rule->dest, rule->dest_depth);
            if (folder) {
#ifdef DEBUG
                printf("Move %s to ", name);
                print_2d_char_array(stdout, rule->dest, rule->dest_depth);
#endif
                move(bookmark_array, i, folder);
                array_size = json_array_size(bookmark_array);
            }
            else {
                fprintf(stderr, "folder: ");
                print_2d_char_array(stderr, rule->dest, rule->dest_depth);
                fprintf(stderr, "not exist, skipped.\n");
            }
        }
        else {
            walk_bookmark_array(root, json_object_get(item, "children"), config);
        }
    }
}

int main(void)
{
    ptr_cfglst cfg = load_configs("rules.conf");

    json_error_t *err = NULL;
    json_t *bookmark = json_load_file("Bookmarks", 0, err);
    json_t *root = json_object_get(bookmark, "roots");
    json_t *child_array =
        json_object_get(
            json_object_get(
                  json_object_get(bookmark, "roots"),
            "bookmark_bar"),
        "children");

#ifdef DEBUG
    printf("Let's see bookmark before sort:\n");
    print_bookmark_array(child_array);
    printf("\nThat's all\n\n");
#endif

    walk_bookmark_array(root, child_array, cfg);

#ifdef DEBUG
    printf("Let's see bookmark after sort:\n");
    print_bookmark_array(child_array);
    printf("\nThat's all\n");
#else
    char *json_out = json_dumps(bookmark, JSON_INDENT(3));
    printf("%s\n", json_out);
    free(json_out);
#endif

    json_decref(bookmark);
    free_configs(cfg);
    return 0;
}
